import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { LoginStore } from '@/store/login'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/index.vue'),
    meta: { title: '登录' },
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/home/index.vue'),
    redirect: '/welcome',
    meta: { title: '首页' },
    children: [
      {
        path: '/welcome',
        name: 'Welcome',
        component: () => import('@/views/welcome/index.vue'),
        meta: { title: '控制台' },
      },
      {
        path: '/personal',
        name: 'Personal',
        component: () => import('@/views/personal/index.vue'),
        meta: { title: '个人中心' },
      },
      {
        path: '/base/admin',
        name: 'SysAdmin',
        component: () => import('@/views/auth/admin/index.vue'),
        meta: { title: '管理员管理' },
      },
      {
        path: '/base/role',
        name: 'SysRole',
        component: () => import('@/views/auth/role/index.vue'),
        meta: { title: '角色管理' },
      },
      {
        path: '/base/menu',
        name: 'SysMenu',
        component: () => import('@/views/auth/rule/index.vue'),
        meta: { title: '菜单管理' },
      },
      {
        path: '/base/dept',
        name: 'SysDept',
        component: () => import('@/views/auth/dept/index.vue'),
        meta: { title: '部门管理' },
      },
      {
        path: '/base/post',
        name: 'SysPost',
        component: () => import('@/views/auth/post/index.vue'),
        meta: { title: '岗位管理' },
      },
      {
        path: '/monitor/operator',
        name: 'SysOperator',
        component: () => import('@/views/log/operation/index.vue'),
        meta: { title: '操作日志' },
      },
      {
        path: '/monitor/loginLog',
        name: 'SysLoginLog',
        component: () => import('@/views/log/login/index.vue'),
        meta: { title: '登录日志' },
      },
    ],
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes,
})

const defaultTitle = import.meta.env.VITE_APP_TITLE

router.beforeEach((to, from, next) => {
  document.title = to.meta.title + '-' + defaultTitle || defaultTitle
  const loginStore = LoginStore()
  if (to.name === 'Login') {
    to.query = {
      redirect: from.path,
    }
    next()
  }
  const token = loginStore.token
  if (!token) {
    return next('/login')
  }

  next()
})

export default router
